package com.grj.community.all;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.grj.community.all.common.RedisKey;
import com.grj.community.all.entity.Post;
import com.grj.community.all.service.PostService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 14505
 */
@SpringBootApplication
@MapperScan("com.grj.community.all.mapper")
//@EnableScheduling
public class AllApplication {

    public static void main(String[] args) {
        SpringApplication.run(AllApplication.class,args);
    }

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private PostService postService;

    @Async
    @Scheduled(cron="*/3 * * * * ?")
    public void scheduled() {
        String now = DateUtil.now();
        String[] s = now.split(" ");
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(RedisKey.VIEW + s[0]);
        if(entries.size() == 0){
            return;
        }
        List<Post> collect = entries.keySet().stream().map(i -> {
            Post post = new Post();
            post.setId(Long.valueOf(i.toString()));
            post.setViews(Long.valueOf(entries.get(i).toString()));
            return post;
        }).collect(Collectors.toList());

        if(collect.size() <= 5000){
            postService.updateBatchById(collect);
            System.out.println("5000");
            System.out.println(collect.size());
            return;
        }
        int size = collect.size()/5000;
        int n = collect.size()%5000;
        List<List<Post>> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            if(i == size - 1){
                list.add(collect.subList(i * 5000, i * 5000 + n));
            }else {
                list.add(collect.subList(i * 5000, i * 5000 + 5000));
            }
        }
        list.forEach(i -> postService.updateBatchById(i));
        System.out.println("100000");
    }
}
